# -*- coding:utf-8 -*-

import web, os
import logging
import traceback
import json
import lib_json as libjson
from utils import DbSession
from plugin import moduleurl
from apscheduler.scheduler import Scheduler
from task import AlarmTask, Monitor, QuitTask
from pager import Pager
from plugin import PingCheck,HttpCheck
 
logging.basicConfig(level = logging.WARN)
logging.getLogger(__name__)


monitor = None
basepath="D:/jiandong/cloudmonitor/html/"
mimesuffix={
            "gif":"image/gif",
            "jpg":"image/jpg",
            "jpeg":"image/jpeg",
            "png":"image/png",
            "bmp":"image/bmp",
            "ico":"image/ico",
            "css":"text/css",
            "js":"application/x-javascript",
            "txt":"text/txt"
            }

class Index:

    def addtask(self):
        with DbSession() as session:
            sql ="""insert into m_services(service_type, service_descr, service_status,check_interval) values('PING','{"hostname":"10.86.11.116","pingcount":5}', 'NEW', 15)"""
            session.update(sql)
            return session.selectone("select max(id) from m_services")

    def GET(self):
        monitor.schedule(QuitTask())
        taskid = self.addtask()
        monitor.schedule(taskid[0])
        return "webpy test`"

class TaskScheduler(object):
    '''add new task into scheduler'''

    def GET(self,name):
        support_method = ["getHttpList","getPingList","deleteMonitor"]
        if not name in support_method:
            return 'No right to GET() access ' + name + '!'
        try:
            func = getattr(self, name)
            return func()
        except Exception,e:
            return "Error: %s" % e
        return "GET task scheduler"

    def POST(self,name):
        support_method = ["addMonitor"]
        if not name in support_method:
            return 'No right to POST() access ' + name + '!'
        try:
            func = getattr(self, name)
            return func()
        except Exception,e:
            traceback.print_exc()
            return "Error: %s" % e
        return "POST task scheduler"

        
    def getMonitorByType(self):
        with DbSession as session:
            data = web.input(jsonform={})
            jsonform = data.jsonform
            value = libjson.read(jsonform)
            sql="select id,service_type,service_status,check_interval,retry_interval,retry_count from m_services where service_type='%s'"
            session.selectall(sql,value['search'])

    def addMonitor(self):
        with DbSession() as session:
            data = web.input(jsonform={})
            jsonform = data.jsonform
            value = libjson.read(jsonform)
            sql ="insert into m_services(service_type, service_descr, service_status,check_interval,retry_interval,retry_count) values('%s','%s','%s','%s','%s','%s')"
            params=self.isMonitorType(value)
            session.update(sql,params)
            self.backinfo = {'rtcode':0,'result':'','message':'insert success'}
            taskid = session.selectone("select max(id) from m_services")
        monitor.schedule(taskid[0])
        return self.backinfo 

    def isMonitorType(self,value):
        if(value['service_type']=="PING"):
            params = (value['service_type'],'{"hostname":"'+value['hostname']+'","pingcount":'+value['pingcount']+"}",value['service_status'],10,value['retry_interval'],value['retry_count'])
        elif(value['service_type']=="HTTP"):
            params = (value['service_type'],'{"url":"'+value['url']+'","timeout":'+value['timeout']+"}",value['service_status'],10,value['retry_interval'],value['retry_count'])
        return params

    def deleteMonitor(self):
        with DbSession() as session:
            data = web.input(jsonform={})
            jsonform = data.jsonform
            value = libjson.read(jsonform)
            sql="delete from m_services where id='%s'"
            session.update(sql,value['id'])
            self.backinfo = {'rtcode':0,'result':'','message':'success'}
        return self.backinfo
class HtmlHandler(object):

    def GET(self, name):
        print name,"---------------"
        fullpath  = os.path.join(basepath ,name)
        web.header('Content-type', "text/html;charset=utf-8")
        try:
            with open(fullpath) as htmlfile:
                return htmlfile.read()
        except:
            return "<h1>Get html file %s failed</h1>" % name

class Other:
    def GET(self,name): 
        try:
            response = open(os.path.join(basepath,name),"r").read()
            suffix = os.path.basename(name).split(".")[-1]
            if suffix in mimesuffix:
                web.header('Content-type', mimesuffix[suffix])
                
        except:
            response = '''<body><h1>Error!</h1>
                        Get file [%s] fail
                        </body>''' % name                            

        web.header('Content-length', str(len(response)))
        return response
    def POST(self,name=""):
        web.header('Content-Type', 'text/html')
        respone = '''<body><h1>Error!</h1>
        Method GET is not allowed for JSONRPC requests
        </body>'''
        return respone


if __name__ == '__main__':
    web.config.debug = True
    urls = moduleurl()+("/", "Index",
            "/(.*\.html)" ,"HtmlHandler",
            "/(.*)","Other"
        )

    app = web.application(urls, globals())

    sched = Scheduler()
    sched.start()
    alarm = AlarmTask()
    alarm.start()
    global monitor
    monitor = Monitor(alarm, sched)
    monitor.start()
    app.run()
